﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardItemModel>
#include <QDebug>
#include <QSettings>
#include <QToolButton>
#include <QSqlQuery>
#include <QCryptographicHash>
#include "qaesencryption.h"
#include "globdataobj.h"
#include "additemdialog.h"
#include <QSqlError>
#include "flatui.h"
#include <QClipboard>
#include "addtypedialog.h"
#include <QUuid>
#include <QDateTime>
#include <QMessageBox>
#include "utils.h"
#include "appsettingdialog.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonDocument>
#include "about.h"
#include "changemainpassdialog.h"

#include "synccontrller.h"



MainWindow::MainWindow(Dbtools *tools,QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    dbtools = tools;

    //设置图标
    this->setWindowIcon(QPixmap(":/new/prefix1/res/w128X128.ico"));
    this->setWindowTitle(setting.applicationName());

    //为窗口添加事件过滤器，以方便后面扩展定时器
    //this->installEventFilter(this);
    connect(ui->actio_changeMainPass,SIGNAL(triggered()),this,SLOT(changeMainPass()));
    connect(ui->actionfile,SIGNAL(triggered()),this,SLOT(test()));


    initTreeView();

    //详情显示面板高度固定为120
    ui->widget_3->setFixedHeight(120);


    initTableWidget();

    initToolButton();
    initStrutsBar();

    addStyle();

    SyncContrller::getInstance()->setDBtool(dbtools);
    //搜索栏获取焦点
    searchLineEdit->setFocus();
    if(setting.value("cloud/activation").isValid()&&setting.value("cloud/activation").toString()=="Y"){
        //已激活云服务
        if(setting.value("cloud/account").isValid()){
            //初始化同步任务

            connect(SyncContrller::getInstance(),SIGNAL(syncAllTypeDataSuccess()),this,SLOT(syncAllTypeSuccess()));
            connect(SyncContrller::getInstance(),SIGNAL(syncAllItemDataSuccess()),this,SLOT(syncAllItemSuccess()));
            connect(SyncContrller::getInstance(),SIGNAL(syncAllTypeDataFail(QString)),this,SLOT(syncAllTypeFail(QString)));
            connect(SyncContrller::getInstance(),SIGNAL(syncAllItemDataFail(QString)),this,SLOT(syncAllItemFail(QString)));

            //触发同步
            SyncContrller::getInstance()->syncAllTypeData();
            SyncContrller::getInstance()->syncAllItemData();
        }
    }


}
void MainWindow::initTreeView(){
    ui->treeView->setFixedWidth(180);
    //树不可编辑
    ui->treeView->setEditTriggers(0);

    treeModel = new QStandardItemModel(ui->treeView);
    treeModel->setHorizontalHeaderLabels(QStringList()<<QStringLiteral("分类名称"));

    ui->treeView->setModel(treeModel);
    //设置树节点不可编辑
    ui->treeView->setEditTriggers(0);
    //ui->tableView->setEditTriggers(0);
    QSqlQuery query(dbtools->getDb());
    query.exec("select * from mytypes where del='N'");

    while(query.next()){
        QStandardItem *item = new QStandardItem(QIcon(query.value("icon").toString()),
                                                query.value("type_name").toString());

        item->setData(query.value("id"));

        treeModel->appendRow(item);
    }

    //设置默认选中第一项
    if(treeModel->rowCount()>0){
        ui->treeView->setCurrentIndex( treeModel->index(0,0,ui->treeView->rootIndex()));
    }


    //初始化右键菜单
    popTreeMenu = new QMenu(ui->treeView);
    QAction *updateType = new QAction();
    QAction *delTypeAction = new QAction();

    delTypeAction->setText(QString("删除"));
    updateType->setText(QString("重命名"));

    popTreeMenu->addAction(updateType);
    popTreeMenu->addAction(delTypeAction);

    connect(updateType,&QAction::triggered,[=](){
        QModelIndex currentIndex = ui->treeView->currentIndex();
        QStandardItem *curritem = treeModel->itemFromIndex(currentIndex);
        QString tid =  curritem->data().toString();

        AddTypeDialog *dlg = new AddTypeDialog(tid,dbtools,this);
        connect(dlg,SIGNAL(saveNewType(QString,QString,QString)),this,
                SLOT(onSaveNewType(QString,QString,QString)));
        dlg->exec();
    });
    connect(delTypeAction,&QAction::triggered,[=](){
        if(QMessageBox::question(this,tr("确认"),
                                 tr("您确定要删除该分类吗？删除该分类后，分类下的所有项也会删除!"),
                                 QMessageBox::Ok|QMessageBox::Cancel,QMessageBox::Cancel)){
            QModelIndex currentIndex = ui->treeView->currentIndex();
            QStandardItem *curritem = treeModel->itemFromIndex(currentIndex);
            QString tid =  curritem->data().toString();

            QSqlQuery query(dbtools->getDb());
            query.prepare("update myitems set del='Y' where type_id=:tid");
            query.bindValue(":tid",tid);
            query.exec();
            query.clear();

            query.prepare("update mytypes set  del='Y' where id=:id");
            query.bindValue(":id",tid);
            if(query.exec()){
                treeModel->removeRow(currentIndex.row());
            }else{
                QMessageBox::critical(this,tr("错误"),tr("删除失败！"));
            }
        }
    });

    ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->treeView,SIGNAL(customContextMenuRequested(QPoint)),this,
            SLOT(treeContextMenu(QPoint)));
}
void MainWindow::updateTreeData(){
    treeModel->clear();

    QSqlQuery query(dbtools->getDb());
    query.exec("select * from mytypes where del='N'");
    while(query.next()){
        QStandardItem *item = new QStandardItem(QIcon(query.value("icon").toString()),
                                                query.value("type_name").toString());

        item->setData(query.value("id"));
        treeModel->appendRow(item);
    }
    treeModel->setHorizontalHeaderLabels(QStringList()<<QStringLiteral("分类名称"));
}
void MainWindow::treeContextMenu(QPoint pos){
    auto index = ui->treeView->indexAt(pos);
    if(index.isValid()){
        popTreeMenu->exec(QCursor::pos());
    }
}
void MainWindow::initTableWidget(){

    //ui->tableView->horizontalHeader()->setStretchLastSection(true);

    //ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->setColumnCount(4);
    ui->tableWidget->setColumnHidden(2,true);
    ui->tableWidget->setColumnHidden(3,true);
    //隔行变色
    ui->tableWidget->setAlternatingRowColors(true);
    //获取默认选中的项
    QStandardItem *item = treeModel->itemFromIndex(ui->treeView->currentIndex());
    if(item!=nullptr){
        QString tid = item->data().toString();
        updateTableData(tid);
    }


    QStringList headerList;
    headerList<<"账号"<<"备注";
    ui->tableWidget->setHorizontalHeaderLabels(headerList);

    ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);//支持右键菜单
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);//只能选择单行
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    //必须要先设置数据，才能设置列宽属性
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Interactive);

    //添加右键菜单
    popMenu = new QMenu(ui->tableWidget);
    QAction *delItemAction = new QAction();
    QAction *updateItemAction =  new QAction();
    QAction *copyAccountAction = new QAction();
    QAction *copyPassAction = new QAction();

    copyAccountAction->setText(QString("复制账号"));
    copyPassAction->setText(QString("复制密码"));
    delItemAction->setText(QString("删除"));
    updateItemAction->setText(QString("修改"));

    connect(copyAccountAction,&QAction::triggered,[=](){
        int row = ui->tableWidget->currentRow();
        QClipboard *board = QApplication::clipboard();
        board->setText(ui->tableWidget->item(row,0)->text());
    });

    connect(copyPassAction,&QAction::triggered,[=](){
        int row = ui->tableWidget->currentRow();
        QClipboard *board = QApplication::clipboard();
        board->setText(ui->tableWidget->item(row,2)->text());
    });
    connect(delItemAction,&QAction::triggered,[=](){
       if(QMessageBox::question(this,tr("确定要删除？"),tr("您确定要删除此项吗？"),
                                QMessageBox::Ok|QMessageBox::Cancel,QMessageBox::Ok)==QMessageBox::Ok){
           QSqlQuery query(dbtools->getDb());
           query.prepare("update myitems set del='Y' where id=:id");
           int row = ui->tableWidget->currentRow();
           query.bindValue(":id",ui->tableWidget->item(row,3)->text());
           if(query.exec()){
               ui->tableWidget->removeRow(row);
           }else{
               QMessageBox::critical(this,tr("错误"),tr("删除失败！"));
           }

       }
    });
    connect(updateItemAction,&QAction::triggered,[=](){
       int row = ui->tableWidget->currentRow();
       AddItemDialog *dlg = new AddItemDialog(dbtools,ui->tableWidget->item(row,3)->text(),this);
       connect(dlg,SIGNAL(saveItem(PassItem *)),this,SLOT(addItemDialog_ok_button_clicked(PassItem *)));
       dlg->exec();
    });

    popMenu->addAction(copyAccountAction);
    popMenu->addAction(copyPassAction);
    popMenu->addAction(delItemAction);
    popMenu->addAction(updateItemAction);

    connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,
            SLOT(slotContextMenu(QPoint)));

    //左键点击事件
    connect(ui->tableWidget,&QTableView::clicked,[=](){
       int row = ui->tableWidget->currentRow();
       ui->account_lineEdit->setText( ui->tableWidget->item(row,0)->text());
       ui->pass_lineEdit->setText(ui->tableWidget->item(row,2)->text());
       ui->beizhu_textEdit->setText(ui->tableWidget->item(row,1)->text());
    });

}
void MainWindow::addStyle(){
    FlatUI::Instance()->setPushButtonQss(ui->account_pushButton,5, 8, "#3498DB", "#FFFFFF", "#5DACE4", "#E5FEFF", "#2483C7", "#A0DAFB");
    FlatUI::Instance()->setPushButtonQss(ui->pass_pushButton,5, 8, "#3498DB", "#FFFFFF", "#5DACE4", "#E5FEFF", "#2483C7", "#A0DAFB");
    FlatUI::Instance()->setLineEditQss(ui->account_lineEdit);
    FlatUI::Instance()->setLineEditQss(ui->pass_lineEdit);
    //ui->account_lineEdit->setReadOnly(true);
}

void MainWindow::refreshCurrentItemsList()
{
    QModelIndex index =  ui->treeView->currentIndex();
    QStandardItem *item = treeModel->itemFromIndex(index);
    QString str = item->data().toString();

    updateTableData(str);
}

void MainWindow::showAboutWindow(bool b)
{
    qDebug()<<"show about";
    about *a = new about(this);
    a->show();
}

void MainWindow::changeMainPass()
{
    changeMainPassDialog *dlg = new changeMainPassDialog(this);
    dlg->exec();
}

void MainWindow::test()
{
    qDebug()<<"test";
}



void MainWindow::closeEvent(QCloseEvent *event)
{

    if(setting.contains("app/Tract") && setting.value("app/Tract").toString()=="Y"){
        event->ignore();
        this->hide();
        if(mySysTrayIcon==nullptr){
            //新建QSystemTrayIcon对象
            mySysTrayIcon = new QSystemTrayIcon(this);
            mySysTrayIcon->setIcon(QIcon(":/new/prefix1/res/w48X48.ico"));
            mySysTrayIcon->setToolTip(setting.applicationName());
            //增加槽函数
            connect(mySysTrayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                    this,SLOT(myTryIconActive(QSystemTrayIcon::ActivationReason)));
            mySysTrayMenu = new QMenu(this);
            QAction *showMainUiAction = new QAction(QString("显示主界面"),this);
            showMainUiAction->setIcon(QIcon(":/new/prefix1/res/application_view_list.png"));
            connect(showMainUiAction,&QAction::triggered,[=](){
               this->show();
            });
            QAction *exitAction = new QAction(QString("退出"),this);
            exitAction->setIcon(QIcon(":/new/prefix1/res/rss_go.png"));
            connect(exitAction,&QAction::triggered,[=](){
               exit(0);
            });
            mySysTrayMenu->addAction(showMainUiAction);
            mySysTrayMenu->addAction(exitAction);
            mySysTrayIcon->setContextMenu(mySysTrayMenu);
        }

        //在系统托盘显示图标
        mySysTrayIcon->show();
        mySysTrayIcon->showMessage("消息",setting.applicationName()+"正在后台运行",QIcon(":/new/prefix1/res/w32X32.ico"),3000);
    }else{
        event->accept();
    }

}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if( event->type()==QEvent::HoverMove){
        this->eventTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
    }
    return QMainWindow::eventFilter(watched,event);
}

void MainWindow::initToolButton()
{
    //工具栏bu允许拖动
    ui->mainToolBar->setMovable(false);
    //添加分类按钮
    QToolButton *addType = new QToolButton(this);
    addType->setIcon(QIcon(":/new/prefix1/res/connect.png"));
    addType->setFixedSize(24,24);
    addType->setToolTip(QString("添加分类"));
    ui->mainToolBar->addWidget(addType);
    connect(addType,SIGNAL(clicked()),this,SLOT(newTypeDlg()));

    //添加项按钮
    QToolButton *addItemBtn = new QToolButton(this);
    addItemBtn->setIcon(QIcon(":/new/prefix1/res/add.png"));
    addItemBtn->setFixedSize(24,24);
    addItemBtn->setToolTip("添加密码项");
    ui->mainToolBar->addWidget(addItemBtn);
    connect(addItemBtn,&QToolButton::clicked,[=](){
        AddItemDialog *adialog = new AddItemDialog(dbtools,QString(""),this);
        adialog->setAttribute(Qt::WA_DeleteOnClose);
        connect(adialog,SIGNAL(saveItem(PassItem *)),this,SLOT(addItemDialog_ok_button_clicked(PassItem *)));
        adialog->exec();
    });

    QToolButton *configAppBtn = new QToolButton(this);
    configAppBtn->setIcon(QIcon(":/new/prefix1/res/cog.png"));
    configAppBtn->setFixedSize(24,24);
    configAppBtn->setToolTip("系统设置");
    ui->mainToolBar->addWidget(configAppBtn);
    connect(configAppBtn,&QToolButton::clicked,[=](){
        AppSettingDialog *dlg = new AppSettingDialog(this);
        connect(dlg,SIGNAL(regUserHttpError(QString)),this,SLOT(regUserHttpError(QString)));
        dlg->setWindowTitle(QString("设置"));
        dlg->show();


    });

    //同步按钮
    if(setting.contains("cloud/activation") && setting.value("cloud/activation").toString()=="Y"){
        //已激活云服务
        if(setting.contains("cloud/account") && !setting.value("cloud/account").toString().isEmpty()){
            QToolButton *syncBtn = new QToolButton(this);
            syncBtn->setIcon(QIcon(":/new/prefix1/res/table_refresh.png"));
            syncBtn->setFixedSize(24,24);
            syncBtn->setToolTip("手动同步");
            ui->mainToolBar->addWidget(syncBtn);
            connect(syncBtn,&QToolButton::clicked,[=](){

                //SyncService::get_instance().syncAllData();

                SyncContrller::getInstance()->syncAllTypeData();
                SyncContrller::getInstance()->syncAllItemData();
            });
        }
    }
    QToolButton *appInfoBtn = new QToolButton(this);
    appInfoBtn->setIcon(QIcon(":/new/prefix1/res/information.png"));
    appInfoBtn->setFixedSize(24,24);
    appInfoBtn->setToolTip("关于");
    ui->mainToolBar->addWidget(appInfoBtn);
    connect(appInfoBtn,SIGNAL(clicked(bool)),this,SLOT(showAboutWindow(bool)));



    //添加搜索栏
    QWidget *searchWidget = new QWidget(this);
    //searchWidget->setFixedHeight(30);
    //searchWidget->layout()
    //searchWidget->setStyleSheet("background-color: rgb(255,1, 1)");
    ui->mainToolBar->addWidget(searchWidget);
    QHBoxLayout *searchLayout = new QHBoxLayout(searchWidget);
    searchLayout->setContentsMargins(0,0,0,0);
    QSpacerItem *spacer = new QSpacerItem(40,20,QSizePolicy::Expanding,
                                          QSizePolicy::Minimum);
    searchLineEdit = new QLineEdit(searchWidget);
    searchLineEdit->setFixedWidth(180);
    searchLineEdit->setPlaceholderText("输入检索文字");
    connect(searchLineEdit,&QLineEdit::textChanged,[=](){
       //改变显示的内容
        QString searchTxt = searchLineEdit->text();

        QSqlQuery query(dbtools->getDb());
        query.exec("select * from myitems where del='N'");
        QList<PassItem*> *items = new QList<PassItem*>();
        while(query.next()){
            items->append(new PassItem(query.value("id").toString(),
                                       MyUtils::getDecodStr(query.value("account").toString().replace(QRegExp("\\ "),"+"),key),
                                       MyUtils::getDecodStr(query.value("pass").toString().replace(QRegExp("\\ "),"+"),key),
                                       query.value("firsttime").toString(),
                                       query.value("lasttime").toString(),
                                       query.value("type_id").toString(),
                                       query.value("beizhu").toString()));
        }
        QList<PassItem*> *outItmes = new QList<PassItem*>();
        for(int a=0;a<items->count();a++){
            if(items->at(a)->getAccount().contains(searchTxt)||items->at(a)->getBeiZhu().contains(searchTxt)){
                outItmes->append(items->at(a));
            }
        }
        updateTableData(QString(""),outItmes);
    });

    searchLayout->addItem(spacer);
    searchLayout->addWidget(searchLineEdit);

    FlatUI::Instance()->setLineEditQss(searchLineEdit);
}

void MainWindow::initStrutsBar()
{
    //初始化状态栏
    QLabel *timeLabel = new QLabel();
    timeLabel->setText(QApplication::applicationVersion());
    //非永久的信息，在左侧显示通过addWidget、insertWidget进行插入。同理说是信息实际是widget，可以是按钮等。
    //ui->statusBar->addWidget(timeLabel);
    //永久的信息，不会被覆盖
    ui->statusBar->insertPermanentWidget(0,timeLabel);
    //临时信息，临时信息封装的很简单，不需要自己newwidget了，只需要直接传入信息内容和信息显示时间即可。
    //currentMessage、showMessage、clearMessage，此类信息不需要自行创建widget，
    //想要移除消息可以等showMessage的时间到了自动消失或者主动地使用clear。
    //ui->statusBar->showMessage(tr("这是一个临时显示的文字信息！"),5000);//显示消息，5秒后自动消失
    ui->statusBar->setStyleSheet(QString("QStatusBar{color:red;}"));
    ui->statusBar->showMessage(tr("这是一个临时消息"));//此消息不会自动消失，可以通过clearMessage清除
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_treeView_clicked(const QModelIndex &index)
{
    //清空搜索框
    searchLineEdit->clear();
    //清空详情
    ui->account_lineEdit->clear();
    ui->pass_lineEdit->clear();
    ui->beizhu_textEdit->clear();
    QString str;
    //str += QStringLiteral("选中 %1").arg(index.data().toString());
    //QStandardItemModel *model = static_cast<QStandardItemModel*>(ui->treeView->model());
    QStandardItem *item = treeModel->itemFromIndex(index);
    str = item->data().toString();

    updateTableData(str);
}
void MainWindow::updateTableData(QString tid,QList<PassItem*> *list){
    if(list==nullptr){
        ui->tableWidget->clearContents();
        ui->tableWidget->setRowCount(0);

        QSqlQuery query(dbtools->getDb());
        query.prepare("select * from myitems where type_id=:id and del='N'");
        query.bindValue(":id",tid);
        query.exec();

        int rownum=0;
        while(query.next()){
            ui->tableWidget->setRowCount(ui->tableWidget->rowCount()+1);
            //将空格替换为+号，
            ui->tableWidget->setItem(rownum,0,new QTableWidgetItem(
                MyUtils::getDecodStr( query.value("account").toString().replace(QRegExp("\\ "),"+"),key)));
            ui->tableWidget->setItem(rownum,1,new QTableWidgetItem(
                query.value("beizhu").toString()));
            ui->tableWidget->setItem(rownum,2,new QTableWidgetItem(
                MyUtils::getDecodStr(query.value("pass").toString().replace(QRegExp("\\ "),"+"),key)));
            ui->tableWidget->setItem(rownum,3,new QTableWidgetItem(
                query.value("id").toString()));

            rownum++;
        }
    }else{
        ui->tableWidget->clearContents();
        ui->tableWidget->setRowCount(0);
        for(int x=0;x<list->count();x++){
            ui->tableWidget->setRowCount(x+1);
            ui->tableWidget->setItem(x,0,new QTableWidgetItem(list->at(x)->getAccount()));
            ui->tableWidget->setItem(x,1,new QTableWidgetItem(list->at(x)->getBeiZhu()));
            ui->tableWidget->setItem(x,2,new QTableWidgetItem(list->at(x)->getPass()));
            ui->tableWidget->setItem(x,3,new QTableWidgetItem(list->at(x)->getId()));
        }
    }
}

void MainWindow::newTypeDlg()
{
    AddTypeDialog *dlg = new AddTypeDialog(QString(""),dbtools, this);
    connect(dlg,SIGNAL(saveNewType(QString,QString,QString)),this,
            SLOT(onSaveNewType(QString,QString,QString)));
    dlg->exec();
}
void MainWindow::onSaveNewType(QString tname, QString tid,QString ticon){
    if(tid.isEmpty()){
        //新增
        QSqlQuery query(dbtools->getDb());
        query.prepare("insert into mytypes (id,type_name,firsttime,lasttime,icon,"
                      "synced,del) values (:id,:type_name,:firsttime,:lasttime,:icon,'N','N')");
        query.bindValue(":id",QUuid::createUuid().toString().remove("{").remove("}").remove("-"));
        query.bindValue(":type_name",tname);
        query.bindValue(":firsttime",tr("%1").arg(QDateTime::currentDateTime().toMSecsSinceEpoch()));
        query.bindValue(":lasttime",tr("%1").arg(QDateTime::currentDateTime().toMSecsSinceEpoch()));
        query.bindValue(":icon",ticon);
        query.exec();

    }else{
        //修改
        QSqlQuery query(dbtools->getDb());
        query.prepare("select * from mytypes where id=:id");
        query.bindValue(":id",tid);
        query.exec();
        double d;
        if(query.next()){
            d = query.value("sync_time").isValid()?query.value("sync_time").toDouble():0;
            d +=10;
        }
        query.clear();
        query.prepare("update mytypes set type_name=:tname,lasttime=:lasttime,"
                      "icon=:icon,synced='N',sync_time=:sync_time where id=:id");
        query.bindValue(":tname",tname);
        query.bindValue(":lasttime",tr("%1").arg(QDateTime::currentDateTime().toMSecsSinceEpoch()));
        query.bindValue(":icon",ticon);
        query.bindValue(":id",tid);
        query.bindValue(":sync_time",d);
        query.exec();
    }
    //initTreeView();
    updateTreeData();
    QSettings sett;
    if(sett.value("cloud/activation").isValid() && sett.value("cloud/activation").toString()=="Y"){
        SyncContrller::getInstance()->syncAllTypeData();
    }

}

void MainWindow::myTryIconActive(QSystemTrayIcon::ActivationReason reson)
{
    switch (reson) {
    case QSystemTrayIcon::Trigger:
        //单击
        break;
    case QSystemTrayIcon::DoubleClick:
        //双击
        this->show();
        break;
    default:
        break;
    }
}

void MainWindow::syncAllTypeSuccess()
{
    qDebug()<<"分类同步完成";
    ui->statusBar->setStyleSheet(QString("QStatusBar{color:green;}"));
    ui->statusBar->showMessage(tr("分类同步完成"));//此消息不会自动消失，可以通过clearMessage清除
    //重新加载分类
    initTreeView();
}

void MainWindow::syncAllItemSuccess()
{
    qDebug()<<"项同步完成";
    ui->statusBar->setStyleSheet(QString("QStatusBar{color:green;}"));
    ui->statusBar->showMessage(tr("项同步完成"));//此消息不会自动消失，可以通过clearMessage清除
}

void MainWindow::syncAllTypeFail(QString e)
{
    ui->statusBar->setStyleSheet(QString("QStatusBar{color:red;}"));
    ui->statusBar->showMessage(e);//此消息不会自动消失，可以通过clearMessage清除
}

void MainWindow::syncAllItemFail(QString e)
{
    ui->statusBar->setStyleSheet(QString("QStatusBar{color:red;}"));
    ui->statusBar->showMessage(e);//此消息不会自动消失，可以通过clearMessage清除
}

void MainWindow::regUserHttpError(QString e)
{
    ui->statusBar->setStyleSheet(QString("QStatusBar{color:red;}"));
    ui->statusBar->showMessage(e);//此消息不会自动消失，可以通过clearMessage清除
}

void MainWindow::slotContextMenu(QPoint pos)
{
    qDebug()<<"pos";
    auto index = ui->tableWidget->indexAt(pos);
    if(index.isValid()){
        popMenu->exec(QCursor::pos());
    }
}

void MainWindow::addItemDialog_ok_button_clicked(PassItem *item)
{
    if(item->getId().isEmpty()){
        //新增
        QSqlQuery query(dbtools->getDb());
        query.prepare("insert into myitems (id,account,pass,firsttime,lasttime,type_id,beizhu,synced,del)"
                      " values (:id,:account,:pass,:firsttime,:lasttime,:type_id,:beizhu,'N','N')");
        query.bindValue(":id",QUuid::createUuid().toString().remove("{").remove("}").remove("-"));
        query.bindValue(":account",MyUtils::getEncodStr(item->getAccount(),key));
        query.bindValue(":pass",MyUtils::getEncodStr(item->getPass(),key));
        query.bindValue(":firsttime",item->getFirstTime());
        query.bindValue(":lasttime",item->getLastTime());
        query.bindValue(":type_id",item->getType_Id());
        query.bindValue(":beizhu",item->getBeiZhu());

        query.exec();
        QSqlError error =  query.lastError();
        if(error.isValid()){
            qDebug()<<error.text();
        }

    }else{
        //修改
        QSqlQuery query(dbtools->getDb());
        query.prepare("select * from myitems where id=:id");
        query.bindValue(":id",item->getId());
        query.exec();
        double d;
        if(query.next()){
            d = query.value("sync_time").isValid()?query.value("sync_time").toDouble():0;
            d +=10;
        }

        query.prepare("update myitems set account=:account,pass=:pass,"
             "lasttime=:lasttime,type_id=:type_id,beizhu=:beizhu,synced='N',sync_time=:sync_time where id=:id");
        query.bindValue(":id",item->getId());
        query.bindValue(":account",MyUtils::getEncodStr(item->getAccount(),key));
        query.bindValue(":pass",MyUtils::getEncodStr(item->getPass(),key));
        query.bindValue(":lasttime",item->getLastTime());
        query.bindValue(":type_id",item->getType_Id());
        query.bindValue(":beizhu",item->getBeiZhu());
        query.bindValue(":sync_time",d);

        query.exec();
    }
    //ui->treeView
    refreshCurrentItemsList();
    //触发同步
    QSettings sett;
    if(sett.contains("cloud/activation") && sett.value("cloud/activation").toString()=="Y"){
        SyncContrller::getInstance()->syncAllItemData();
    }

}


void MainWindow::on_account_pushButton_clicked()
{
    QClipboard *board = QApplication::clipboard();
    board->setText(ui->account_lineEdit->text());
}

void MainWindow::on_pass_pushButton_clicked()
{
    QClipboard *board = QApplication::clipboard();
    board->setText(ui->pass_lineEdit->text());
}
